const { parseEntry } = require("./datParser");
const { convertSRTToASSTime } = require("./assStyles");

/**
 * 生成ASS字幕内容
 * @param {Array} entries - 字幕条目数组
 * @param {number} audioDuration - 音频时长（秒），可选参数
 * @returns {string} ASS字幕内容
 */
function generateASSContent(entries, audioDuration = null) {
  let assContent = "";
  const subtitles = [];

  // 首先解析所有条目
  entries.forEach((entry, index) => {
    if (entry.trim() === "") return;
    const parsedEntry = parseEntry("*^" + entry);
    if (parsedEntry) {
      subtitles.push({
        index: index + 1,
        startTime: parsedEntry.startTime,
        endTime: parsedEntry.endTime,
        english: parsedEntry.english,
        chinese: parsedEntry.chinese,
      });
    }
  });

  // 修复字幕时间，确保连续且覆盖整个时间段
  if (subtitles.length > 0) {
    // 确保第一句从0秒开始
    if (subtitles[0]) {
      subtitles[0].startTime = "00:00:00,200";
    }

    // 确保每句之间没有间隙，当前句的结束时间等于下一句的开始时间
    for (let i = 0; i < subtitles.length - 1; i++) {
      if (subtitles[i] && subtitles[i + 1]) {
        subtitles[i].endTime = subtitles[i + 1].startTime;
      }
    }

    // 为最后一句设置结束时间
    const lastSubtitle = subtitles[subtitles.length - 1];
    if (lastSubtitle) {
      if (audioDuration) {
        // 如果提供了音频时长，使用音频时长作为结束时间
        const hours = Math.floor(audioDuration / 3600);
        const minutes = Math.floor((audioDuration % 3600) / 60);
        const seconds = Math.floor(audioDuration % 60);
        const milliseconds = Math.round((audioDuration % 1) * 1000);
        const endTime = `${hours.toString().padStart(2, "0")}:${minutes.toString().padStart(2, "0")}:${seconds.toString().padStart(2, "0")},${milliseconds.toString().padStart(3, "0")}`;
        lastSubtitle.endTime = endTime;
      }
    }
  }

  // 为每个条目生成包含前一帧、当前帧、后一帧的字幕
  subtitles.forEach((subtitle, index) => {
    const prevSubtitle = index > 0 ? subtitles[index - 1] : null;
    const nextSubtitle = index < subtitles.length - 1 ? subtitles[index + 1] : null;

    // 构建三行字幕内容
    const prevLine = prevSubtitle ? `{\\rPrevious}${prevSubtitle.english}\\N${prevSubtitle.chinese}` : "";
    const currentLine = `{\\rCurrent}${subtitle.english}\\N${subtitle.chinese}`;
    const nextLine = nextSubtitle ? `{\\rNext}${nextSubtitle.english}\\N${nextSubtitle.chinese}` : "";

    const dialogText = [prevLine, currentLine, nextLine].filter(line => line !== "").join("\\N");

    // 转换时间格式为ASS格式
    const startAssTime = convertSRTToASSTime(subtitle.startTime);
    const endAssTime = convertSRTToASSTime(subtitle.endTime);

    assContent += `Dialogue: 0,${startAssTime},${endAssTime},Default,,0,0,0,,${dialogText}\n`;
  });

  return assContent;
}

module.exports = {
  generateASSContent,
};
